package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.R;
import com.itheima.dto.OrdersDto;
import com.itheima.entity.OrderDetail;
import com.itheima.entity.Orders;
import com.itheima.entity.ShoppingCart;
import com.itheima.service.OrderDetailService;
import com.itheima.service.OrdersService;
import com.itheima.service.ShoppingCartService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/order")
public class OrdersController {
    @Autowired
    private OrdersService ordersService;
    @Autowired
    private OrderDetailService orderDetailService;
    @Autowired
    private ShoppingCartService shoppingCartService;

    /**
     * 用户下单
     *
     * @param orders
     * @return
     */
    @PostMapping("/submit")
    public R<String> submit(@RequestBody Orders orders) {
        log.info("订单数据：{}", orders);
        ordersService.submit(orders);
        return R.success("下单成功");
    }

    /**
     * 往期订单功能
     *
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/userPage")
    public R userPage(Integer page, Integer pageSize) {
        //1. 接收参数
        log.info("page:{}, pageSize:{}", page, pageSize);
        //2.创建分页查询
        Page<Orders> ordersPage = new Page<>(page, pageSize);
        LambdaQueryWrapper<Orders> lqw = new LambdaQueryWrapper<>();
        lqw.orderByDesc(Orders::getCheckoutTime);
        //先查询出来order的数据
        ordersService.page(ordersPage, lqw);

        Page<OrdersDto> ordersDtoPage = new Page<>(page, pageSize);
        //分页，把数据一部分放入dto
        BeanUtils.copyProperties(ordersPage, ordersDtoPage, "records");

        List<Orders> records = ordersPage.getRecords();
        List<OrdersDto> ordersDtoList = records.stream().map(item -> {
            OrdersDto ordersDto = new OrdersDto();
            BeanUtils.copyProperties(item, ordersDto);

            //通过order的 id 拿到orderDetails的数据
            Long id = item.getId();
            LambdaQueryWrapper<OrderDetail> olqw = new LambdaQueryWrapper<>();
            olqw.eq(id != null, OrderDetail::getOrderId, id);
            List<OrderDetail> orderDetailList = orderDetailService.list(olqw);

            //把数据交给dto
            ordersDto.setOrderDetails(orderDetailList);
            return ordersDto;
        }).collect(Collectors.toList());

        ordersDtoPage.setRecords(ordersDtoList);

        return R.success(ordersDtoPage);
    }

    /**
     * 订单的分页，条件查询
     *
     * @param page
     * @param pageSize
     * @param number
     * @param beginTime
     * @param endTime
     * @return
     */
    @GetMapping("/page")
    public R page(Integer page, Integer pageSize, Long number,
                  @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
                          LocalDateTime beginTime,
                  @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
                          LocalDateTime endTime) {

        //获取参数
        log.info("page:{}, pageSize:{}, number:{}", page, pageSize, number);

        Page<Orders> ordersPage = new Page<>(page, pageSize);
        LambdaQueryWrapper<Orders> olqw = new LambdaQueryWrapper<>();
        //按照下单时间倒排
        olqw.orderByDesc(Orders::getOrderTime);

        //通过模糊查询来查找数据
        olqw.like(number != null, Orders::getNumber, number);

        //按照下单时间来查询
        olqw.between(beginTime != null & endTime != null, Orders::getOrderTime, beginTime, endTime);

        //先查询出来order的数据
        ordersService.page(ordersPage, olqw);

        return R.success(ordersPage);
    }

    /**
     * 派送订单
     *
     * @param orders
     * @return
     */
    @PutMapping
    public R put(@RequestBody Orders orders) {

        //修改数据库中的状态
        ordersService.updateById(orders);

        return R.success("修改成功");
    }

    /**
     * 派送完成后，前端选择再来一单
     *
     * @param orders
     * @return
     */
    @PostMapping("/again")
    public R again(@RequestBody Orders orders, HttpSession session) {
        //1. 先拿到订单详情菜品数据
        Long ordersId = orders.getId();

        LambdaQueryWrapper<OrderDetail> lqw = new LambdaQueryWrapper<>();
        lqw.eq(ordersId != null, OrderDetail::getOrderId, ordersId);
        List<OrderDetail> orderDetailList = orderDetailService.list(lqw);

        //把拿到的数据放入购物车中
        List<ShoppingCart> shoppingCartList = orderDetailList.stream().map(item -> {

            ShoppingCart shoppingCart = new ShoppingCart();
            //把拿到的菜品放入shoppingCart
            BeanUtils.copyProperties(item, shoppingCart);

            //雪花算法生成新的id
            long id = IdWorker.getId();
            shoppingCart.setId(id);

            //设置userId
            Long empId = (Long) session.getAttribute("empId");
            shoppingCart.setUserId(empId);

            shoppingCart.setCreateTime(LocalDateTime.now());

            return shoppingCart;
        }).collect(Collectors.toList());

        //把数据存储到shopping_cart购物车表
        shoppingCartService.saveBatch(shoppingCartList);

        return R.success("再来一单");
    }

}
